package banmuoi.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import banmuoi.entity.*;
import banmuoi.util.HibernateUtil;

@WebServlet("/crudPermission.do")
public class PermissionAdmin extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String page = req.getParameter("page");
		
		Session session = HibernateUtil.openSession();
		
		//HIỆN DANH SÁCH
		String hql = "FROM Permission ORDER BY id DESC";
		Query query = session.createQuery(hql);
		List<Permission> entities = query.list();
		req.setAttribute("showPermission", entities);
		
		
		//REFRESH THỰC THỂ KHI ĐƯỢC GỌI TỚI
		if(req.getParameter("permissionId") != null){
			int permissionId = Integer.parseInt(req.getParameter("permissionId"));
			Permission entity = (Permission) session.load(Permission.class, permissionId);
			req.setAttribute("entityPermission", entity);
		}
		
			
		/*if(page!=null){
			if(page.equals("product") ){
				
			}
		}
		else {*/
			req.getRequestDispatcher("admin/PermissionAdmin.jsp").forward(req, resp);
		//}
		
		session.close();
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String id = req.getParameter("txtId");
		String page = req.getParameter("txtPage");
		String disable = req.getParameter("txtDisable");
		
		Session session = HibernateUtil.openSession();
		Transaction trans = session.beginTransaction();
		
		try{
			if(req.getParameter("btnCreate") != null){
				Permission entity = new Permission();
				
				session.save(entity);
				req.setAttribute("error", "Inserted successfully !");
			}
			else if(req.getParameter("btnUpdate") != null){
				Permission entity = new Permission();
				
				
				session.update(entity);
				req.setAttribute("error", "Updated successfully !");
			}
			else if(req.getParameter("btnDelete") != null){
				Admin entity = new Admin(); 
				
				entity.setId(Integer.valueOf(id));
				
				session.delete(entity);
				req.setAttribute("error", "Deleted successfully !");
			}
			
			
			trans.commit();
		}
		catch (Exception e) {
			trans.rollback();
			req.setAttribute("error", e.getMessage());
		}
		
		session.close();
		this.doGet(req, resp);
	}
}
